package com.xxxx.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.AdminUtils;
import com.xxxx.config.jwt.JwtTokenUtil;
import com.xxxx.mapper.AdminMapper;
import com.xxxx.mapper.AdminRoleMapper;
import com.xxxx.mapper.RoleMapper;
import com.xxxx.pojo.Admin;
import com.xxxx.pojo.AdminRole;
import com.xxxx.pojo.R;
import com.xxxx.pojo.Role;
import com.xxxx.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chao
 * @since 2022-09-26
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private JwtTokenUtil jwtTokenUtils;

@Autowired
private AdminMapper adminMapper;

@Autowired
private RoleMapper roleMapper;

@Autowired
private AdminRoleMapper adminRoleMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHeader;




    @Override
    public Admin getAdminByUsername(String username) {
        Admin admin = adminMapper.selectOne(
                new QueryWrapper<Admin>().eq("username", username).eq("enabled", true));
        return admin;
    }

    @Override
    public R login(String username, String password, String code, HttpServletRequest request) {
        String captcha = request.getSession().getAttribute("captcha").toString();
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return R.error("验证码错误，请重新输入！");
        }

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return R.error("用户名密码错误！");
        }
        if (!userDetails.isEnabled()) {
            return R.error("该账号已被禁用!");
        }

        //更新security中的登陆用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //生成token
        String token = jwtTokenUtils.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead", tokenHeader);

        return R.success("登陆成功！",tokenMap);
    }
    /**
     * 根据用户id查询角色
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);

    }

    @Override
    public R getAllAdmins(String keywords) {
        List<Admin> adminList=  adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(), keywords);
        return R.success(adminList);
    }
    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public R update(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new LambdaQueryWrapper<AdminRole>().eq(AdminRole::getAdminId, adminId));
       Integer result= adminRoleMapper.update(adminId, rids);
        if (result==rids.length) {
            return R.success("更新成功！");
        }
        return R.error("更新失败！");
    }

    @Override
    public R updateAdminPassword(String ordPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (passwordEncoder.matches(ordPass,admin.getPassword())) {
            admin.setPassword(passwordEncoder.encode(pass));
            adminMapper.updateById(admin);
            return R.success("更新密码成功！");
        }
        return R.error("原密码错误，更新失败！");
    }
}
